const { appId, appsecret } = require('../uteil')
const axios = require('axios')
const fs = require('fs')
module.exports = {

    //请求jsapi_ticket
    getJsapiTicket(access_token) {
        return new Promise((resolve, reject) => {
        	axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`).then(res => {
                // console.log('请求到jsapi_ticket',res.data);
                
                this.saveJsapiTicket(res.data)
                resolve()
            }).catch(err=>{
            	console.log('请求错误',err)
            })
        	
            // axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appsecret}`).then(res => {
            //     console.log('请求到jsapi_ticket',res.data);
                
            //     this.saveJsapiTicket(res.data)
            //     resolve()
            // }).catch(err=>{
            // 	console.log('请求错误',err)
            // })
        })
    },

    //判断是否过期
     isValueJsapiTicket(expires_in) {
        return expires_in > Date.now()
    },

    //保存jsapi_ticket
    saveJsapiTicket(data) {

        //当前时间加2小时后 -5分钟
        data.expires_in = Date.now() + (data.expires_in - 300) * 1000

        fs.writeFile(__dirname + '/../data/jsapiTicket.txt', JSON.stringify(data), (err) => {
            if (err) {
                console.log('写入错误', err);

            } else {
                // console.log('写入成功');

            }
        })
    },

    //读取jsapi_ticket
    readJsapiTicket() {
        return new Promise((resolve, reject) => {

            fs.readFile(__dirname + '/../data/jsapiTicket.txt', (err, data) => {

                if (!err) {
                    // console.log('jsapi_ticket文件读取成功');
                    if (data.length > 0) {
                        resolve(JSON.parse(data))
                    } else {
                        console.log('jsapi_ticket文件为空');
                        reject()
                    }
                } else {
                    console.log('jsapi_ticket文件读取失败', err);
                    reject()
                }
            })
        })
    },

    //拿到一个可用的Jsapi_ticket
    fetchJsapiTicket(access_token) {
        return new Promise((resolve, reject) => {

            //从本地读取
            this.readJsapiTicket()
                .then(async res => {
                    //如果没有过期则返回
                    if (this.isValueJsapiTicket(res.expires_in)) {
                    	// console.log('jsapi_ticket没有过期')
                        resolve(res)
                    } else {
						console.log('jsapi_ticket已过期')
                        //如果过期了则重新请求后返回
                        await this.getJsapiTicket(access_token)
                        let result = await this.readJsapiTicket()
                        resolve(result)
                    }
                })
                .catch(async err => {
                    //如果读取失败了则重新请求后返回
                    await this.getJsapiTicket(access_token)
                    let result = await this.readJsapiTicket()
                    resolve(result)
                })
        })
    }
}